from nicegui import ui
import pandas as pd
from analysis.data_loader import load_titanic_data, get_column_info
from analysis.data_cleaner import clean_titanic_data
from analysis.data_analyzer import analyze_titanic_data
from visualization.plotly_charts import (
    create_survival_by_class,
    create_age_distribution,
    create_fare_vs_age,
    create_correlation_heatmap
)

USERNAME = 'admin'
PASSWORD = '123456'

# 全局会话变量
session = {'logged_in': False}

@ui.page('/login')
def login_page():
    with ui.card().classes('absolute-center w-96'):
        ui.label('Titanic 数据分析平台登录').classes('text-2xl mb-4')
        username = ui.input('用户名').classes('w-full')
        password = ui.input('密码', password=True).classes('w-full')
        error_label = ui.label('').classes('text-red-500')
        def try_login():
            if username.value == USERNAME and password.value == PASSWORD:
                session['logged_in'] = True
                ui.navigate.to('/dashboard')
            else:
                error_label.text = '用户名或密码错误'
        ui.button('登录', on_click=try_login).classes('w-full mt-2')
        ui.separator()
        error_label

@ui.page('/dashboard')
def dashboard_page():
    if not session.get('logged_in'):
        ui.navigate.to('/login')
        return
    with ui.header().classes('bg-blue-800 text-white shadow-lg'):
        with ui.row().classes('w-full items-center justify-between'):
            ui.label('泰坦尼克号数据分析平台').classes('text-2xl font-bold')
            ui.button('登出', on_click=logout).props('flat').classes('bg-blue-600 hover:bg-blue-700')
    # 数据加载与分析
    raw_df = load_titanic_data()
    if raw_df is not None:
        df = clean_titanic_data(raw_df)
        analysis_results = analyze_titanic_data(df)
        column_info = get_column_info(df)
        with ui.tabs().classes('w-full bg-blue-50') as tabs:
            ui.tab('数据概览', icon='table_chart')
            ui.tab('数据清洗', icon='cleaning_services')
            ui.tab('生存分析', icon='show_chart')
            ui.tab('特征关系', icon='scatter_plot')
            ui.tab('相关性分析', icon='heat_map')
        with ui.tab_panels(tabs, value='数据概览').classes('w-full flex-grow'):
            with ui.tab_panel('数据概览'):
                ui.label('原始数据样本').classes('text-lg font-bold mb-2')
                ui.table(columns=[{'name': col, 'label': col, 'field': col} for col in df.head(10).columns],
                         rows=df.head(10).to_dict('records')).classes('max-h-96')
                ui.label('数据列信息').classes('text-lg font-bold mt-4 mb-2')
                ui.table(columns=[
                        {'name': 'name', 'label': '列名', 'field': 'name'},
                        {'name': 'dtype', 'label': '类型', 'field': 'dtype'},
                        {'name': 'unique', 'label': '唯一值', 'field': 'unique'},
                        {'name': 'missing', 'label': '缺失值', 'field': 'missing'},
                        {'name': 'missing_percent', 'label': '缺失率(%)', 'field': 'missing_percent'},
                    ],
                    rows=column_info).classes('max-h-96')
            with ui.tab_panel('数据清洗'):
                ui.label('清洗后数据样本').classes('text-lg font-bold mb-2')
                ui.table(columns=[{'name': col, 'label': col, 'field': col} for col in df.head(10).columns],
                         rows=df.head(10).to_dict('records')).classes('max-h-96')
                ui.markdown('''
                - **年龄(Age)**: 用中位数填充缺失值
                - **登船港口(Embarked)**: 用众数填充缺失值
                - **船舱(Cabin)**: 标记为"Unknown"
                - **特征工程**: FamilySize, IsAlone, Title
                - **特征转换**: Sex, Embarked, Title 映射为数值
                - **特征选择**: 删除 PassengerId, Name, Ticket, Cabin
                ''')
            with ui.tab_panel('生存分析'):
                ui.label('三维舱位生存率').classes('text-lg font-bold mb-2')
                fig1 = create_survival_by_class(df)
                if fig1 is not None:
                    ui.plotly(fig1).classes('w-full h-[480px]')
                ui.label('三维年龄分布与生存情况').classes('text-lg font-bold mt-4 mb-2')
                fig2 = create_age_distribution(df)
                if fig2 is not None:
                    ui.plotly(fig2).classes('w-full h-[480px]')
            with ui.tab_panel('特征关系'):
                ui.label('票价-年龄二维关系（按生存状态）').classes('text-lg font-bold mb-2')
                fig3 = create_fare_vs_age(df)
                if fig3 is not None:
                    ui.plotly(fig3).classes('w-full h-[480px]')
            with ui.tab_panel('相关性分析'):
                ui.label('特征相关性热力图').classes('text-lg font-bold mb-2')
                fig4 = create_correlation_heatmap(df)
                if fig4 is not None:
                    ui.plotly(fig4).classes('w-full h-[480px]')
    else:
        ui.label('数据加载失败').classes('text-red-500')

def logout():
    session['logged_in'] = False
    ui.navigate.to('/login')

@ui.page('/')
def main_page():
    if session.get('logged_in'):
        ui.navigate.to('/dashboard')
    else:
        ui.navigate.to('/login')

ui.run(title='Titanic数据分析平台', port=8080, reload=False)